<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? t('common.edit') : t('common.create')"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleModalCancel"
    :destroyOnClose="true"
    :minHeight="500"
    :width="1000"
  >
    <Form
      ref="formRef"
      :model="formData"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="rules"
    >
      <Row>
        <Divider orientation="left">{{
          t('routes.demo.fileTypeSetting.basicPropertySetting')
        }}</Divider>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.fileTypeIdentification')" name="name">
            <Input
              v-model:value="formData.name"
              :placeholder="t('routes.demo.fileTypeSetting.fileTypeIdentificationPlaceholder')"
              :readonly="isUpdate"
            />
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem
            :label="t('routes.demo.fileTypeSetting.producingSoftware')"
            name="producingSoftware"
          >
            <Input
              v-model:value="formData.producingSoftware"
              :placeholder="t('routes.demo.fileTypeSetting.producingSoftwarePlaceholder')"
              :readonly="isUpdate"
            />
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.extension')" name="extension">
            <Input
              v-model:value="formData.extension"
              :placeholder="t('routes.demo.fileTypeSetting.extensionPlaceholder')"
              :readonly="isUpdate"
            />
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.icon')">
            <Upload
              list-type="picture-card"
              v-model:file-list="formData.icon"
              @preview="handlePreview"
              @change="handleChange"
            >
              <div v-if="formData.icon.length < 2">
                <Icon icon="ant-design:plus-outlined" />
                <div class="ant-upload-text">{{ t('common.upload') }}</div>
              </div>
            </Upload>
            <Modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </Modal>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Divider orientation="left">{{
          t('routes.demo.fileTypeSetting.mainDocumentBrowsingMethod')
        }}</Divider>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.browser')">
            <Select
              v-model:value="formData.mainBrowser"
              :placeholder="t('routes.demo.fileTypeSetting.browserPlaceholder')"
            >
              <SelectOption v-for="item in mainBrowserList" :value="item.id" :key="item.id"
                >{{ item.resourceName }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.chrome')">
            <Input
              v-model:value="formData.mainChrome"
              :placeholder="t('routes.demo.fileTypeSetting.chromePlaceholder')"
            />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Divider orientation="left">{{
          t('routes.demo.fileTypeSetting.attachedDocumentBrowsingMethod')
        }}</Divider>
        <Col span="24">
          <FormItem>
            <Checkbox v-model:checked="formData.hasAttachedDocument">{{
              t('routes.demo.fileTypeSetting.hasAttachedDocument')
            }}</Checkbox>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.browser')">
            <Input
              v-model:value="formData.otherBrowser"
              :placeholder="t('routes.demo.fileTypeSetting.browserPlaceholder')"
              readonly
            />
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.chrome')">
            <Input
              v-model:value="formData.otherChrome"
              :placeholder="t('routes.demo.fileTypeSetting.chromePlaceholder')"
              :disabled="!formData.hasAttachedDocument"
            />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Divider orientation="left">{{
          t('routes.demo.fileTypeSetting.lightweightFileSetting')
        }}</Divider>
        <Col span="24">
          <FormItem>
            <Checkbox v-model:checked="formData.hasLightweightFile">{{
              t('routes.demo.fileTypeSetting.hasLightweightFile')
            }}</Checkbox>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem :label="t('routes.demo.fileTypeSetting.lightweightFileExtension')">
            <Input
              v-model:value="formData.lightweightFileExtension"
              :placeholder="t('routes.demo.fileTypeSetting.lightweightFileExtensionPlaceholder')"
              :disabled="!formData.hasLightweightFile"
            />
          </FormItem>
        </Col>
      </Row>
    </Form>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Icon } from '/@/components/Icon';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    Row,
    Col,
    Form,
    FormItem,
    Input,
    Divider,
    Upload,
    Modal,
    Select,
    SelectOption,
    Checkbox,
  } from 'ant-design-vue';
  import { createFileType, getFileTypeById, updateFileType } from '/@/api/demo/system';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { GetResourceList } from '/@/api/demo/dict';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref<boolean>(false);
  const formData = ref<any>({
    name: '', // 文件类型标识
    producingSoftware: '', // 生产软件
    extension: '', // 文件扩展名
    icon: [], // 图标
    mainBrowser: undefined, // 主通用浏览器
    mainChrome: '', // 主第三方浏览器
    hasAttachedDocument: false, // 是否有附属文档
    otherBrowser: undefined, // 附件通用浏览器
    otherChrome: '', // 附件第三方浏览器
    hasLightweightFile: false, // 是否有轻量化文件
    lightweightFileExtension: '', // 轻量化文件扩展名
  });
  const labelCol = ref<any>({ span: 6 });
  const wrapperCol = ref<any>({ span: 16 });
  const previewVisible = ref<boolean>(false);
  const previewImage = ref<string>('');
  const mainBrowserList = ref<any>([]);
  const formRef = ref();
  const ischangeico = ref<string>('0');

  const rules = {
    name: [
      {
        required: true,
        message: t('routes.demo.fileTypeSetting.fileTypeIdentificationPlaceholder'),
        trigger: 'blur',
      },
    ],
    producingSoftware: [
      {
        required: true,
        message: t('routes.demo.fileTypeSetting.producingSoftwarePlaceholder'),
        trigger: 'blur',
      },
    ],
    extension: [
      {
        required: true,
        message: t('routes.demo.fileTypeSetting.extensionPlaceholder'),
        trigger: 'blur',
      },
    ],
  };

  // 提交
  async function handleSubmit() {
    formRef.value.validate().then(() => {
      setModalProps({ confirmLoading: true });
      console.log(formData.value);
      if (isUpdate.value) {
        // 修改
        try {
          if (formData.value.icon.length >= 2) {
            const newData = new FormData();
            newData.append('pdmfileid', formData.value.name);
            newData.append('pdmfileext', formData.value.extension);
            newData.append('pdmcreatesoft', formData.value.producingSoftware);
            newData.append('pdmattach', formData.value.hasAttachedDocument ? '1' : '0');
            newData.append('pdmviewsoft', formData.value.mainChrome);
            newData.append('pdmviewocx', formData.value.mainBrowser);
            newData.append('pdmattachview', formData.value.lightweightFileExtension);
            newData.append('pdmremark', formData.value.otherChrome);
            newData.append('ischangeico', ischangeico.value);
            newData.append('file1', formData.value.icon[0].originFileObj);
            newData.append('file2', formData.value.icon[1].originFileObj);
            updateFileType(newData).then((res) => {
              if (res) {
                createMessage.success(t('common.saveSuccess'));
                emit('success');
                handleModalCancel();
              }
            });
          } else {
            createMessage.warn(t('routes.demo.fileTypeSetting.iconUpload'));
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      } else {
        // 新增
        try {
          if (formData.value.icon.length >= 2) {
            const newData = new FormData();
            newData.append('pdmfileid', formData.value.name);
            newData.append('pdmfileext', formData.value.extension);
            newData.append('pdmcreatesoft', formData.value.producingSoftware);
            newData.append('pdmattach', formData.value.hasAttachedDocument ? '1' : '0');
            newData.append('pdmviewsoft', formData.value.mainChrome);
            newData.append('pdmviewocx', formData.value.mainBrowser);
            newData.append('pdmattachview', formData.value.lightweightFileExtension);
            newData.append('pdmremark', formData.value.otherChrome);
            newData.append('ischangeico', '1');
            newData.append('file1', formData.value.icon[0].originFileObj);
            newData.append('file2', formData.value.icon[1].originFileObj);
            createFileType(newData).then((res) => {
              if (res) {
                createMessage.success(t('common.saveSuccess'));
                emit('success');
                handleModalCancel();
              }
            });
          } else {
            createMessage.warn(t('routes.demo.fileTypeSetting.iconUpload'));
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
    });
  }

  // 退出
  const handleModalCancel = () => {
    formData.value = {
      name: '', // 文件类型标识
      producingSoftware: '', // 生产软件
      extension: '', // 文件扩展名
      icon: [], // 图标
      mainBrowser: undefined, // 主通用浏览器
      mainChrome: '', // 主第三方浏览器
      hasAttachedDocument: false, // 是否有附属文档
      otherBrowser: undefined, // 附件通用浏览器
      otherChrome: '', // 附件第三方浏览器
      hasLightweightFile: false, // 是否有轻量化文件
      lightweightFileExtension: '', // 轻量化文件扩展名
    };
    ischangeico.value = '0';
    closeModal();
  };

  // 图标预览
  function getBase64(file: File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = (await getBase64(file.originFileObj)) as string;
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
  };

  const handleCancel = () => {
    previewVisible.value = false;
  };

  const handleChange = () => {
    ischangeico.value = '1';
  };

  // 定义弹窗是否可见
  const [register, { closeModal, setModalProps }] = useModalInner((data) => {
    isUpdate.value = !!data?.isUpdate;
    // 获取文件类型设置通用浏览器下拉列表
    GetResourceList({ TypeName: '预览方式' }).then((res) => {
      mainBrowserList.value = res;
    });
    if (isUpdate.value) {
      getFileTypeById(data.currentRow.id).then((res) => {
        formData.value.name = res.pdmfileid;
        formData.value.producingSoftware = res.pdmcreatesoft;
        formData.value.extension = res.pdmfileext;
        let newUrl = res.fileIcoUrl.replace(/#/g, '%23');
        let newUrl2 = res.fileIcoEffectUrl.replace(/#/g, '%23');
        formData.value.icon = [
          {
            url: newUrl,
          },
          {
            url: newUrl2,
          },
        ];
        formData.value.mainBrowser = res.pdmviewocx === 'undefined' ? undefined : res.pdmviewocx;
        formData.value.mainChrome = res.pdmviewsoft === 'null' ? '' : res.pdmviewsoft;
        formData.value.hasAttachedDocument = res.pdmattach === '1';
        formData.value.otherBrowser = undefined;
        formData.value.otherChrome = res.pdmremark === 'null' ? '' : res.pdmremark;
        formData.value.hasLightweightFile = res.pdmattachview !== null;
        formData.value.lightweightFileExtension =
          res.pdmattachview === 'null' ? '' : res.pdmattachview;
      });
    }
  });
</script>

<style lang="less" scoped>
  ::v-deep(.ant-upload-select-picture-card i) {
    font-size: 32px;
    color: #999;
  }

  ::v-deep(ant-upload-select-picture-card .ant-upload-text) {
    margin-top: 8px;
    color: #666;
  }
</style>
